// pages/addprofrom/addprofrom.js
import { addServiceItem, delItem } from '../../../utils/networkRequest.js'
import { errorMsg } from '../../../utils/tool.js'

const app = getApp()

Page({
  data: {
    classifyArr: [],
    classIndex: "",//所选中的分类索引
    itemName: "", //项目名称
    remark: "",//项目介绍
    price: "",//项目价格
    isEdit: false,//是否是修改
    id: "",//项目id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.isEdit) {
      let item = JSON.parse(options.item) 
      this.setData({
        classifyArr: app.globalData.itemList,
        isEdit: options.isEdit,
        itemName: item.title,
        price: item.price,
        remark: item.memo,
        classIndex: item.index,
        id: item.id
      })
    } else {
      this.setData({
        classifyArr: app.globalData.itemList,
      })
    }
  },
  //选择分类
  bindClassChange: function (e) {
    this.setData({
      classIndex: e.detail.value
    })
  },
  //项目名称
  itemNameChange: function (e) {
    this.setData({
      itemName: e.detail.detail.value
    })
  },
  //项目价格
  priceChange: function (e) {
    this.setData({
      price: e.detail.detail.value
    })
  },
  //项目介绍
  remarkChange: function (e) {
    this.setData({
      remark: e.detail.detail.value
    })
  },
  //删除项目
  onDelSubmit: function () {
    let self = this;
    delItem(this.data.id, (r) => {
      if (r.code == 0) {
         
          app.globalData.itemList = r.data;
          wx.navigateBack();
       
      } else {
        errorMsg(r.message)
      } 
    })
  },
  //添加项目
  onAddSubmit: function () {
    let { itemName, price, remark, classIndex, classifyArr, id } = this.data;
    if (!itemName) {
      errorMsg("项目名称为空");
    } else if (!price) {
      errorMsg("项目价格为空")
    } else if (classIndex === "") {
      errorMsg("项目分类为空")
    } else {
      addServiceItem(id, itemName, price, remark, classifyArr[classIndex].id, (r) => {
        if (r.code == 0) {
          app.globalData.itemList = r.data;
          wx.navigateBack();
        } else {
          errorMsg(r.message)
        }
      })
    }

  }

})